import Vue from 'vue'
import Vuex from 'vuex'

import { getRequest } from '@/utils/request.js'
import { Notification } from 'element-ui'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

Vue.use(Vuex)
const now = new Date()

const store = new Vuex.Store({
  state: {
    admins: [], //用户列表
    routes: [], //路由
    currentAdmin: JSON.parse(sessionStorage.getItem('user')), //当前登陆的用户
    currentSession: {}, //当前聊天框里面选中的用户
    filterKey: '',
    sessions: {}, //存储聊天记录
    idDot: {}, //控制小红点的显示和隐藏 用来做头像旁边的消息提示

    stomp: null,
  },
  mutations: {
    initRoutes(state, data) {
      state.routes = data
    },
    changeCurrentSession(state, currentSession) {
      state.currentSession = currentSession
      //点击过后 小红点不出现了
      Vue.set(state.idDot, state.currentAdmin.username + '#' + state.currentSession.username, false)
    },
    addMessage(state, msg) {
      let message = state.sessions[state.currentAdmin.username + '#' + msg.to]
      // console.log("message是什么",message);
      if (!message) {
        // 如果message为空，则初始化一个[] 这里将state.sessions变成响应式
        Vue.set(state.sessions, state.currentAdmin.username + '#' + msg.to, [])
      }
      state.sessions[state.currentAdmin.username + '#' + msg.to].push({
        content: msg.content,
        date: new Date(),
        //发消息的人是我自己(传过来的msg身上并没有notSelf属性，因此!msg.notSelf = true)
        // 如果是别人发我的 此时notSelf为true， 置反就为self
        self: !msg.notSelf,
      })
    },
    INIT_DATA(state) {
      /**
       * 每次上线从浏览器的localStorage里获取历史聊天记录进行初始化
       */
      let data = localStorage.getItem('vue-chat-session')
      // console.log('data存在吗',data);
      if (data) {
        state.sessions = JSON.parse(data)
      }
    },

    //初始化好友列表
    INIT_AdMINS(state, adminsList) {
      state.admins = adminsList
    },
  },
  actions: {
    connect(context) {
      context.state.stomp = Stomp.over(new SockJS('/ws/ep'))
      const token = sessionStorage.getItem('token')
      context.state.stomp.connect(
        { 'Auth-Token': token },
        (success) => {
          //订阅消息 /user必须加
          context.state.stomp.subscribe('/user/queue/chat', (msg) => {
            let receiveMsg = JSON.parse(msg.body)
            console.log('msg的格式:', msg)
            console.log('receiveMsg是什么', receiveMsg)
            //如果我当前没有选中任何人进行聊天 或者 我选中了但当前聊天的人和发消息给我的人不是同一个人
            if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
              //弹出 "xxx发来消息" 的提示
              Notification.success({
                title: `${receiveMsg.fromNickName}发来消息`,
                // 只显示message的前10个字符
                message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) : receiveMsg.content,
                type: 'success',
                position: 'bottom-right',
              })
              // 在头像旁边设置红点 表示我没看到过
              Vue.set(context.state.idDot, context.state.currentAdmin.username + '#' + receiveMsg.from, true)
            }
            receiveMsg.notSelf = true //别人发给我的
            receiveMsg.to = receiveMsg.from
            context.commit('addMessage', receiveMsg)
          })
        },
        (error) => {}
      )
    },

    async initData(context) {
      //初始化聊天记录
      context.commit('INIT_DATA')
      //初始化聊天用户列表
      const data = await getRequest('/system/admin/')
      if (data) {
        context.commit('INIT_AdMINS', data)
      }
    },
  },
  modules: {},
})

store.watch(
  (state) => {
    //getter 监听到聊天记录发生变化时 会触发下面的函数 从而更新localStorage的聊天记录
    return state.sessions
  },
  (val) => {
    console.log('CHANGE: ', val)
    // console.log('保存了吗',localStorage.getItem('vue-chat-session'));
    localStorage.setItem('vue-chat-session', JSON.stringify(val))
  },
  {
    deep: true /*这个貌似是开启watch监测的判断,官方说明也比较模糊*/,
  }
)

export default store
